package com.zbkj.crmeb.front.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.zbkj.crmeb.chant.dto.ChannelMerchantDTO;
import com.zbkj.crmeb.store.dao.StoreSaleAnalysisDao;
import com.zbkj.crmeb.store.intercept.RateLimiter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.config.MybatisPlusConfig;
import com.crmeb.core.utils.TableNameUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.utils.DateUtil;
import com.utils.EuropeUtil;
import com.utils.ImageSearchUtils;
import com.utils.PriceUtil;
import com.utils.ProductUtil;
import com.utils.RestTemplateUtil;
import com.utils.SourceProductUtil;
import com.utils.ThreadPoolUtils;
import com.utils.vo.MatchImageVo;
import com.zbkj.crmeb.category.service.CategoryService;
import com.zbkj.crmeb.category.vo.CategoryTreeVo;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.BarCodeEnum;
import com.zbkj.crmeb.enums.CategoryTypeEnum;
import com.zbkj.crmeb.enums.CrmebMerchantEnums;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.enums.StockAreaTempEnum;
import com.zbkj.crmeb.enums.SuppliersIdEnum;
import com.zbkj.crmeb.front.request.IndexStoreProductSearchRequest;
import com.zbkj.crmeb.front.request.ProductRequest;
import com.zbkj.crmeb.front.response.BuyerProductResDTO;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.Product;
import com.zbkj.crmeb.front.response.BuyerProductResDTO.ProductSku;
import com.zbkj.crmeb.front.response.ProductDetailResponse;
import com.zbkj.crmeb.front.response.ProductResponse;
import com.zbkj.crmeb.front.response.StoreProductReplayCountResponse;
import com.zbkj.crmeb.front.service.ProductService;
import com.zbkj.crmeb.store.dao.StoreProductDao;
import com.zbkj.crmeb.store.dto.ImItemResDTO;
import com.zbkj.crmeb.store.dto.ImItemResDTO.ImItemDTO;
import com.zbkj.crmeb.store.dto.ImProductInfoResDTO;
import com.zbkj.crmeb.store.dto.ImProductInfoResDTO.ImProductInfoDTO;
import com.zbkj.crmeb.store.dto.ImProductResDTO.ImProductDTO;
import com.zbkj.crmeb.store.dto.ImProductResDTO.ImProductItemDTO;
import com.zbkj.crmeb.store.model.EuropeProduct;
import com.zbkj.crmeb.store.model.EuropeProductSku;
import com.zbkj.crmeb.store.model.EuropeProductSkuMerged;
import com.zbkj.crmeb.store.model.StoreBrand;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.model.StoreProductActive;
import com.zbkj.crmeb.store.model.StoreProductAttr;
import com.zbkj.crmeb.store.model.StoreProductAttrResult;
import com.zbkj.crmeb.store.model.StoreProductAttrValue;
import com.zbkj.crmeb.store.model.StoreProductDescription;
import com.zbkj.crmeb.store.model.StoreProductMer;
import com.zbkj.crmeb.store.model.Supplier;
import com.zbkj.crmeb.store.request.StoreProductAttrValueRequest;
import com.zbkj.crmeb.store.request.StoreProductCrmebRequest;
import com.zbkj.crmeb.store.request.StoreProductReplySearchRequest;
import com.zbkj.crmeb.store.response.PriceResult;
import com.zbkj.crmeb.store.response.StoreCartResponse;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductReplyResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.response.StoreProductStoreInfoResponse;
import com.zbkj.crmeb.store.service.ChannelCategoryConfigService;
import com.zbkj.crmeb.store.service.StoreBrandService;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreProductAttrResultService;
import com.zbkj.crmeb.store.service.StoreProductAttrService;
import com.zbkj.crmeb.store.service.StoreProductAttrValueService;
import com.zbkj.crmeb.store.service.StoreProductDescriptionService;
import com.zbkj.crmeb.store.service.StoreProductMerService;
import com.zbkj.crmeb.store.service.StoreProductRelationService;
import com.zbkj.crmeb.store.service.StoreProductReplyService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.store.service.StoreSaleAnalysisService;
import com.zbkj.crmeb.store.service.SupplierService;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemAttachmentService;
import com.zbkj.crmeb.system.service.SystemConfigService;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;

/**
 * @author Mr.Zhang
 * @Description IndexServiceImpl 接口实现
 * @since 2020-04-13
 */
@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    private ExecutorService thread = ThreadPoolUtils.getThread();
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreProductMerService storeProductMerService;
    @Autowired
    private StoreProductAttrService storeProductAttrService;
    @Autowired
    private StoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    private StoreProductAttrResultService storeProductAttrResultService;
    @Autowired
    private StoreProductDescriptionService storeProductDescriptionService;
    @Autowired
    private SystemAttachmentService systemAttachmentService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private StoreProductReplyService storeProductReplyService;
    @Autowired
    private UserService userService;
    @Autowired
    private StoreProductRelationService storeProductRelationService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    EuropeUtil europeUtil;
    @Autowired
    ProductUtil productUtil;
    @Autowired
    SourceProductUtil sourceProductUtil;
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Resource
    private StoreProductDao dao;
    @Autowired
    SupplierService supplierService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ChannelCategoryConfigService channelCategoryConfigService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private StoreSaleAnalysisService storeSaleAnalysisService;
    @Autowired
    private StoreSaleAnalysisDao storeSaleAnalysisDao;
    private ExecutorService executor = ThreadPoolUtils.getThread();

    /**
     * 首页产品的轮播图和产品信息
     *
     * @param request IndexStoreProductSearchRequest 参数
     * @return CommonPage<ProductResponse>
     * @author Mr.Zhang
     * @since 2020-06-02
     */
    @Override
    public CommonPage<ProductResponse> getIndexProduct(IndexStoreProductSearchRequest request, PageParamRequest pageParamRequest) {
        // db 查不到商品,去搜索查
        /*if(StringUtils.isNotBlank(request.getKeywords()) && CollectionUtils.isEmpty(storeProductList)){
            storeProductList = queryBySearch(request,pageParamRequest);
        }*/
        List<StoreProduct> storeProductList = new ArrayList<>();
        if (StringUtils.isNotBlank(request.getAttrs()) || !Objects.isNull(request.getMaxPrice()) || !Objects.isNull(request.getMinPrice())) {
            storeProductList = storeProductService.selectProductList(request, pageParamRequest);
        } else {
            storeProductList = storeProductService.getList(request, pageParamRequest);
        }
        CommonPage<StoreProduct> storeProductCommonPage = CommonPage.restPage(storeProductList);
        if (CollectionUtils.isEmpty(storeProductList)) {
            return CommonPage.restPage(new ArrayList<>());
        }
        List<ProductResponse> productResponseArrayList = new ArrayList<>();
        //处理返回数据
        dealProductResponse(storeProductList, productResponseArrayList);

        CommonPage<ProductResponse> productResponseCommonPage = CommonPage.restPage(productResponseArrayList);
        BeanUtils.copyProperties(storeProductCommonPage, productResponseCommonPage, "list");
        return productResponseCommonPage;
    }

    /**
     * 商品列表 - 处理返回数据
     *
     * @param storeProductList
     * @param productResponseArrayList
     */
    private void dealProductResponse(List<StoreProduct> storeProductList, List<ProductResponse> productResponseArrayList) {
        log.info("进入ProductServiceImpl类方法 dealProductResponse ，参数{}", storeProductList);

        for (StoreProduct storeProduct : storeProductList) {
            ProductResponse productResponse = new ProductResponse();
            BeanUtils.copyProperties(storeProduct, productResponse);
            productResponse.setCateId(Collections.singletonList(storeProduct.getCateId()));
            productResponse.setPrice(productResponse.getPrice().setScale(2));
            productResponse.setStockArea(StockAreaTempEnum.getByTempId(storeProduct.getTempId()).getStockAreaCode());
            productResponse.setStockAreaName(StockAreaTempEnum.getByTempId(storeProduct.getTempId()).getStockAreaName());
            productResponse.setSales(storeProduct.getSales());

            //品牌处理
            StoreBrand storeBrand = storeBrandService.getByBrandId(storeProduct.getBrandId());
            if (null == storeBrand) {
                storeBrand = new StoreBrand();
                storeBrand.setEnName("OTHER");
            }
            productResponse.setBrand(storeBrand);

            //市场价和折扣处理
            dealCalcDiscount(productResponse, storeProduct);

            //主图和详情图压缩替换处理
            compressProductImage(productResponse, storeProduct);

            productResponseArrayList.add(productResponse);
        }
    }

    /**
     * 商品列表 - 主图和详情图压缩替换处理
     */
    private void compressProductImage(ProductResponse productResponse, StoreProduct storeProduct) {

        //详情图
        String sliderImage = storeProduct.getSliderImage();

        if (StringUtils.isNotBlank(sliderImage)) {
            List<String> sliderImageList = JSONObject.parseArray(sliderImage, String.class);
            productResponse.setSliderImage(sliderImageList);
        }
    }

    /**
     * 商品列表 - 市场价和折扣处理
     *
     * @param productResponse
     */
    private void dealCalcDiscount(ProductResponse productResponse, StoreProduct storeProduct) {

        productResponse.setDiscount(null);
        productResponse.setOtPrice(null);

        //市场价和折扣处理
        BigDecimal otPrice = storeProduct.getOtPrice();
        BigDecimal calcDiscount = new BigDecimal(0);

        //市场价不为null或市场价大于0
        if (null != otPrice && otPrice.compareTo(new BigDecimal(0)) > 0) {
            productResponse.setOtPriceRmb(priceUtil.eur2RmbStatic(otPrice, storeProduct.getExchangeRate()));
            //折扣 = 售价/(市场价*汇率) , 注：市场价为港币
            calcDiscount = priceUtil.calcDiscount(storeProduct.getPrice(), otPrice, storeProduct.getExchangeRate());
        }
        if (null != calcDiscount && !(calcDiscount.compareTo(BigDecimal.ZERO) == 0)) {
            productResponse.setDiscount(calcDiscount.toString() + "折");
            productResponse.setOtPrice(storeProduct.getOtPrice());
        }
    }

    /**
     * 获取分类
     *
     * @return List<CategoryTreeVo>
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @Override
    public List<CategoryTreeVo> getCategory() {
        return categoryService.getFrontListTree(Constants.CATEGORY_TYPE_PRODUCT, 1);
    }

    /**
     * 商品列表
     *
     * @return CommonPage<ProductResponse>
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @Override
    @RateLimiter(qps = 15, timeout = 1, timeUnit = TimeUnit.SECONDS)
    public CommonPage<ProductResponse> getList(ProductRequest request, PageParamRequest pageParamRequest) throws Exception {
        IndexStoreProductSearchRequest indexStoreProductSearchRequest = new IndexStoreProductSearchRequest();
        BeanUtils.copyProperties(request, indexStoreProductSearchRequest);
        //条件查询
        productListConditionSearch(request, indexStoreProductSearchRequest);
        return getIndexProduct(indexStoreProductSearchRequest, pageParamRequest);
    }

    /**
     * 商品列表 - 图搜
     *
     * @return CommonPage<ProductResponse>
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @Override
    @RateLimiter(qps = 10, timeout = 1, timeUnit = TimeUnit.SECONDS)
    public CommonPage<ProductResponse> getListByTuSou(MultipartFile targetImage, ProductRequest request, PageParamRequest pageParamRequest) throws Exception {
        IndexStoreProductSearchRequest indexStoreProductSearchRequest = new IndexStoreProductSearchRequest();
        BeanUtils.copyProperties(request, indexStoreProductSearchRequest);

        //条件查询
        productListConditionSearch(request, indexStoreProductSearchRequest);

        if (null != targetImage && !targetImage.isEmpty()) {
            //图像搜索
            productListSearchImage(targetImage, indexStoreProductSearchRequest);
        }

        return getIndexProduct(indexStoreProductSearchRequest, pageParamRequest);
    }

    /**
     * 图像搜索 - 以图搜图
     *
     * @param searchRequest
     */
    private void productListSearchImage(MultipartFile targetImage, IndexStoreProductSearchRequest searchRequest) throws Exception {

        List<String> barCodeArr = new ArrayList<>();

        //搜索相似图片barCode
        byte[] imgBytes = targetImage.getBytes();
        List<MatchImageVo> matchList = ImageSearchUtils.searchImage(imgBytes);

        //赋值barCode集合查询
        if (CollectionUtils.isNotEmpty(matchList)) {
            for (MatchImageVo matchImage : matchList) {
                String entityId = matchImage.getProductId();
                if (StringUtils.isNotBlank(entityId)) {
                    barCodeArr.add(entityId);
                }
            }
        }
        //图搜结果barCode集合作为查询条件
        searchRequest.setBarCodeArr(barCodeArr);
    }

    /**
     * 商品列表 - 条件查询
     */
    private void productListConditionSearch(ProductRequest request, IndexStoreProductSearchRequest indexStoreProductSearchRequest) {

        List<Integer> categoryIdList;
        if (request.getCid() != null && request.getCid() != 0) {
            //查找当前类下的所有子类
//            List<CategoryMatch> childVoListByPid = categoryMatchService.getChildVoListByPid(request.getCid());
            List<CategoryMatch> childVoListByPid = categoryMatchService.getThreeChildVoListByPid(request.getCid());
//            List<Category> childVoListByPid = categoryService.getChildVoListByPid(request.getCid());
            categoryIdList = childVoListByPid.stream().map(CategoryMatch::getId).collect(Collectors.toList());

            categoryIdList.add(request.getCid());
            indexStoreProductSearchRequest.setCateId(categoryIdList);
        }
        if (request.getCids() != null && request.getCids() != "") {
            String[] cid = request.getCids().split(",");
            categoryIdList = new ArrayList<Integer>();
            for (String id : cid) {
                categoryIdList.add(Integer.parseInt(id));
                indexStoreProductSearchRequest.setCateId(categoryIdList);
            }
        }
        indexStoreProductSearchRequest.setType(1);
        indexStoreProductSearchRequest.setKeywords(request.getKeyword());
        indexStoreProductSearchRequest.setIsNew(request.getNews());
        indexStoreProductSearchRequest.setStockArea(request.getStockArea());
        indexStoreProductSearchRequest.setBrandIds(request.getBrandIds());
    }

    /**
     * 商品详情
     *
     * @return ProductDetailResponse
     * @author Mr.Zhang Edit by stivpeim 2020-6-30
     * @since 2020-06-03
     */
    @Override
    public ProductDetailResponse getDetail(Integer id) {
        ProductDetailResponse productDetailResponse = new ProductDetailResponse();

        try {
            StoreProduct storeProduct = storeProductService.getById(id);
            // 更新时间超过一小时的商品重新获取
            if (null != storeProduct && null != storeProduct.getLastPushTime() && 60 < ((System.currentTimeMillis() - storeProduct.getLastPushTime().getTime()) / 1000 / 60)) {
                updateProductByNow(storeProduct);
            }

            StoreProductResponse productResponse = storeProductService.getByProductId(id);
            StoreProductStoreInfoResponse storeInfo = new StoreProductStoreInfoResponse();
            BeanUtils.copyProperties(productResponse, storeInfo);
            storeInfo.setVideoLink(productResponse.getVideo());

            if (productResponse.getBrandId() != null) {
                StoreBrand storeBrand = storeBrandService.getByBrandId(productResponse.getBrandId());
                if (storeBrand != null) {
                    storeInfo.setBrandName(storeBrand.getEnName());
                } else {
                    storeInfo.setBrandName("OTHER");
                }
            }
            storeInfo.setUserLike(false);
            storeInfo.setUserCollect(false);
            // 设置点赞和收藏
            User user = userService.getInfo();
            if (null != user && null != user.getUid()) {
                storeInfo.setUserLike(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), id, true).size() > 0);
                storeInfo.setUserCollect(storeProductRelationService.getLikeOrCollectByUser(user.getUid(), id, false).size() > 0);
                user = userService.updateForPromoter(user);
                productDetailResponse.setPriceName(getPacketPriceRange(productResponse, user.getIsPromoter()));
            }

            // 通过原价算折扣率
            if (storeInfo.getOtPrice() != null && storeInfo.getOtPrice().intValue() > 0) {
                BigDecimal bigDecimal = priceUtil.calcDiscount(storeInfo.getPrice(), storeInfo.getOtPrice(), productResponse.getExchangeRate());
                if (null != bigDecimal) {
                    storeInfo.setDiscount(bigDecimal.toString() + "折");
                }
            }

            storeInfo.setStockAreaName(StockAreaTempEnum.getByTempId(storeInfo.getTempId()).getStockAreaName());
            storeInfo.setSales(storeInfo.getSales());
            productDetailResponse.setStoreInfo(storeInfo);

            // 根据制式设置attr属性
            setSkuAttr(id, productDetailResponse, productResponse);

            //记录商品访客数量 author:duyb
            try {
                saveVisitorNumber(storeProduct);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("记录商品访客数量出错!,exception:", e);
            }
            // 优品推荐
//            List<StoreProduct> storeProducts = storeProductService.getRecommendStoreProduct(storeInfo.getBrandId(), 18);
//            List<StoreProductRecommendResponse> storeProductRecommendResponses = new ArrayList<>();
//            for (StoreProduct product : storeProducts) {
//                StoreProductRecommendResponse sPRecommendResponse = new StoreProductRecommendResponse();
//                BeanUtils.copyProperties(product, sPRecommendResponse);
//                sPRecommendResponse.setActivity(null); // todo 暂放 设置优品推荐中的拼团砍价秒杀属性
//                //            sPRecommendResponse.setCheckCoupon(storeCouponService.getListByUser(product.getId()).size() > 0);
//                storeProductRecommendResponses.add(sPRecommendResponse);
//            }
//            productDetailResponse.setGoodList(storeProductRecommendResponses);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return productDetailResponse;
    }

    /**
     * 记录商品访客数量
     *
     * @author duyb
     * @since 2020-10-12
     */
    private void saveVisitorNumber(StoreProduct storeProduct) {
        StoreProductActive storeProductActive = storeSaleAnalysisService.getOne(Wrappers.<StoreProductActive>lambdaQuery()
                .eq(StoreProductActive::getMerId, storeProduct.getMerId())
                .eq(StoreProductActive::getProductId, storeProduct.getId())
                .eq(StoreProductActive::getStatisticsDate, DateUtil.nowDateTimeReturnDate("yyyy-MM-dd"))
        );
        if (storeProductActive == null) {
            storeProductActive = new StoreProductActive();
            storeProductActive.setMerId(storeProduct.getMerId());
            storeProductActive.setProductId(storeProduct.getId());
            storeProductActive.setCreateTime(DateUtil.nowDateTime());
            storeProductActive.setVisitorNumber(1);
            storeProductActive.setStatisticsDate(DateUtil.nowDateTimeReturnDate("yyyy-MM-dd"));
        } else {
            storeProductActive.setVisitorNumber(storeProductActive.getVisitorNumber() + 1);
        }
        storeSaleAnalysisService.saveOrUpdate(storeProductActive);

    }

    /**
     * 评论列表
     *
     * @return List<StoreProductReply>
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @Override
    public PageInfo<StoreProductReplyResponse> getReplyList(Integer id, Integer type, PageParamRequest pageParamRequest) {
        StoreProductReplySearchRequest storeProductReplySearchRequest = new StoreProductReplySearchRequest();
        storeProductReplySearchRequest.setIsDel(false);
        storeProductReplySearchRequest.setProductId(id.toString());
        storeProductReplySearchRequest.setType(type);
        return storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
    }

    /**
     * 产品评价数量和好评度
     *
     * @return StoreProductReplayCountResponse
     * @author Mr.Zhang
     * @since 2020-06-03
     */
    @Override
    public StoreProductReplayCountResponse getReplyCount(Integer id) {
        PageParamRequest pageParamRequest = new PageParamRequest();
        pageParamRequest.setLimit(1);

        StoreProductReplySearchRequest storeProductReplySearchRequest = new StoreProductReplySearchRequest();
        storeProductReplySearchRequest.setIsDel(false);
        storeProductReplySearchRequest.setProductId(id.toString());
        storeProductReplySearchRequest.setType(1);
        PageInfo<StoreProductReplyResponse> storeProductReplyServiceList = storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
        Long goodCount = storeProductReplyServiceList.getTotal();

        storeProductReplySearchRequest.setType(2);
        storeProductReplyServiceList = storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
        Long inCount = storeProductReplyServiceList.getTotal();

        storeProductReplySearchRequest.setType(3);
        storeProductReplyServiceList = storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
        Long poorCount = storeProductReplyServiceList.getTotal();

        Long sumCount = goodCount + inCount + poorCount;

        //5星评分星数
        storeProductReplySearchRequest.setType(0);
        storeProductReplySearchRequest.setStar(5);
        storeProductReplyServiceList = storeProductReplyService.getList(storeProductReplySearchRequest, pageParamRequest);
        Long starCount = storeProductReplyServiceList.getTotal();

        //好评率
        String replyChance = "0";
        if (sumCount > 0 && starCount > 0) {
            replyChance = String.format("%.2f", ((starCount.doubleValue() / sumCount.doubleValue())));
        }

        Integer replyStar = storeProductReplyService.getSumStar(id);

        return new StoreProductReplayCountResponse(sumCount, goodCount, inCount, poorCount, replyChance, replyStar);
    }

    /**
     * 设置制式结构给attr属性
     *
     * @param id                    产品id
     * @param productDetailResponse 商品详情
     * @param productResponse       商品本身
     */
    private void setSkuAttr(Integer id, ProductDetailResponse productDetailResponse, StoreProductResponse productResponse) {
        List<HashMap<String, Object>> attrMapList = new ArrayList<>();
        // 根据制式设置sku属性
        HashMap<String, StoreProductAttrValueResponse> skuMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(productResponse.getAttrValue())) {
            for (StoreProductAttrValueResponse attrValue : productResponse.getAttrValue()) {
                // 过滤掉没有库存的商品
                if (attrValue.getStock() > 0) {
                    skuMap.put(attrValue.getSuk(), attrValue);
                }
            }
        }

        productDetailResponse.setProductValue(skuMap);
        if (CollectionUtils.isNotEmpty(productResponse.getAttr())) {
            for (StoreProductAttr attr : productResponse.getAttr()) {
                HashMap<String, Object> attrMap = new HashMap<>();
                attrMap.put("productId", attr.getProductId());
                attrMap.put("attrName", attr.getAttrName());
                attrMap.put("type", attr.getType());

                List<String> attrValues = new ArrayList<>();
                String trimAttr = attr.getAttrValues().replace("[", "").replace("]", "");
                if (attr.getAttrValues().contains(",")) {
                    attrValues = Arrays.asList(trimAttr.split(","));
                } else {
                    attrValues.add(trimAttr);
                }

                // 过滤掉没有库存的sku
                //            attrValues = attrValues.stream().filter(s->skuMap.containsKey(s)).collect(Collectors.toList());

                attrMap.put("attrValues", attrValues);
                // 设置带有优惠券标识的sku集合
                List<HashMap<String, Object>> attrValueMapList = new ArrayList<>();
                for (String attrValue : attrValues) {
                    HashMap<String, Object> attrValueMap = new HashMap<>();
                    attrValueMap.put("attr", attrValue);
                    attrValueMapList.add(attrValueMap);
                }
                attrMap.put("attrValue", attrValueMapList);
                attrMapList.add(attrMap);
            }
        }
        productDetailResponse.setProductAttr(attrMapList);
    }

    /**
     * 获取商品佣金区间
     *
     * @param storeProductResponse 商品属性
     * @param isPromoter           是否推荐人
     * @return String 金额区间
     */
    @Override
    public String getPacketPriceRange(StoreProductResponse storeProductResponse, boolean isPromoter) {
        String priceName = "0";
        if (!isPromoter) {
            return priceName;
        }
        // 获取拥挤比例
        String BrokerageRatioString = systemConfigService.getValueByKey("store_brokerage_ratio");
        BigDecimal BrokerRatio = new BigDecimal(0);
        if (StringUtils.isNotBlank(BrokerageRatioString)) {
            BrokerRatio = new BigDecimal(BrokerageRatioString).multiply(new BigDecimal(0.01).setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }
        BigDecimal maxPrice = null;
        BigDecimal minPrice = null;
        // 获取佣金比例区间 todo 这里的对象更换为map后需要重新计算
        if (storeProductResponse.getIsSub()) { // 是否单独分拥
            maxPrice = storeProductResponse.getAttrValue().stream().map(e -> e.getBrokerage()).reduce(BigDecimal.ZERO, BigDecimal::max);
            minPrice = storeProductResponse.getAttrValue().stream().map(e -> e.getBrokerage()).reduce(BigDecimal.ZERO, BigDecimal::min);
        } else {
            if (CollectionUtils.isNotEmpty(storeProductResponse.getAttrValue())) {
                BigDecimal _maxPrice = storeProductResponse.getAttrValue().stream().map(e -> e.getBrokerage()).reduce(BigDecimal.ZERO, BigDecimal::max);
                BigDecimal _minPrice = storeProductResponse.getAttrValue().stream().map(e -> e.getBrokerage()).reduce(BigDecimal.ZERO, BigDecimal::min);
                maxPrice = BrokerRatio.multiply(_maxPrice);
                minPrice = BrokerRatio.multiply((_minPrice));
            } else {
                maxPrice = BigDecimal.ZERO;
                minPrice = BigDecimal.ZERO;
            }
        }
        if (minPrice.compareTo(BigDecimal.ZERO) == 0 && maxPrice.compareTo(BigDecimal.ZERO) == 0) {
            priceName = "0";
        } else if (minPrice.compareTo(BigDecimal.ZERO) == 0 && maxPrice.compareTo(BigDecimal.ZERO) == 1) {
            priceName = maxPrice.toString();
        } else if (minPrice.compareTo(BigDecimal.ZERO) == 1 && maxPrice.compareTo(BigDecimal.ZERO) == 1) {
            priceName = minPrice.toString();
        } else if (minPrice.compareTo(maxPrice) == 0 && minPrice.compareTo(BigDecimal.ZERO) == 0) {
            priceName = maxPrice.toString();
        } else {
            priceName = minPrice.toString() + "~" + maxPrice.toString();
        }
        return priceName;
    }

    @Override
    public Integer getStockCount(Integer productId, String sourceSkuId, String size) {
        Integer count = 0;
        List<StoreOrderInfo> orderInfoList = storeOrderInfoService.getStoreOrderInfoList(productId);
        if (null != orderInfoList && orderInfoList.size() > 0) {
            for (StoreOrderInfo info : orderInfoList) {
                StoreCartResponse cart = JSON.parseObject(info.getInfo(), StoreCartResponse.class);
                //根据sourceSkuId 判断是否buyer
                if (StringUtils.isNotBlank(sourceSkuId)) {
                    if (sourceSkuId.equals(cart.getProductInfo().getAttrInfo().getSourceSkuId())) {
                        count = cart.getCartNum() + count;
                    }
                } else {
                    // 欧洲的 根据size判断 订单的数量
                    String[] sukArr = cart.getProductInfo().getAttrInfo().getSuk().split(",");
                    if (cart.getProductInfo().getAttrInfo().getSuk().contains(",")) {
                        if (size.equals(sukArr[1])) {
                            count = cart.getCartNum() + count;
                        }
                    } else {
                        if (size.equals(sukArr[0])) {
                            count = cart.getCartNum() + count;
                        }
                    }
                }
            }
        }
        return count;
    }

    @Override
    public Integer getStockCountUnpaid(List<Integer> productIds, List<Integer> activityIds) {
        Integer count = 0;
        List<StoreOrderInfo> orderInfoList = storeOrderInfoService.getStoreOrderInfoListUnPaid(productIds, activityIds);
        if (null != orderInfoList && orderInfoList.size() > 0) {
            for (StoreOrderInfo info : orderInfoList) {
                StoreCartResponse cart = JSON.parseObject(info.getInfo(), StoreCartResponse.class);
                count = cart.getCartNum() + count;
            }
        }
        return count;
    }

    /**
     * 实时更新商品数据
     *
     * @param @param storeProduct
     * @return void
     * @throws
     * @Description:
     * @author daigb
     */
    @Override
    public void updateProductByNow(StoreProduct storeProduct) {
        String barCode = storeProduct.getBarCode();
        Callable<String> call = new Callable<String>() {
            @Override
            public String call() throws Exception {
                // buyer商品
                if (ProductTypeEnum.valueOf(storeProduct.getIsEurope()) == ProductTypeEnum.BUYER) {
                    BuyerProductResDTO buyerProductResDTO = productUtil.getBuyerProductByBarCode(barCode);
                    // 处理主表数据
                    List<Product> buyerProducts = buyerProductResDTO.getProduct();
                    if (CollectionUtils.isEmpty(buyerProducts)) {
                        log.info("--------------- 实时查询buyer商品, 未取到数据, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    Product buyerProduct = buyerProducts.get(0);
                    // 金额不对时商品下架
                    if (Integer.parseInt(buyerProduct.getSalePrice()) <= 0) {
                        log.info("--------------- 实时查询buyer商品, 商品金额不是正常值, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 不可售商品下架
                    if (0 == buyerProduct.getOnSale()) {
                        log.info("--------------- 实时查询buyer商品, 商品不可售下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 去除sku信息过滤库存为0的
                    int stock = 0;
                    List<ProductSku> buyerSkus = buyerProduct.getSkus();
                    List<ProductSku> productSkus = new ArrayList<ProductSku>();
                    for (ProductSku sku : buyerSkus) {
                        if (0 < sku.getStock()) {
                            stock += sku.getStock();
                            productSkus.add(sku);
                        }
                    }
                    // 没有规格时商品下架
                    if (CollectionUtils.isEmpty(productSkus)) {
                        log.info("--------------- 实时查询buyer商品, 商品没有正常库存规格, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 处理价格
                    buyerProduct = sourceProductUtil.priceAdjustBuyer2Crmeb(buyerProduct);
                    // 构建实体
                    StoreProductCrmebRequest storeProductCrmebRequest = sourceProductUtil.buildCrmebProduct(buyerProduct, productSkus);
                    saveProduct(storeProductCrmebRequest, storeProduct, stock);
                    // 欧洲商品
                } else if (ProductTypeEnum.valueOf(storeProduct.getIsEurope()) == ProductTypeEnum.EUROPE) {
                    EuropeProduct europeProduct = productUtil.getEuropeByBarCode(barCode);
                    // 没有查询到商品
                    if (null == europeProduct || CollectionUtils.isEmpty(europeProduct.getSkuList())) {
                        log.info("--------------- 实时查询europe商品, 未取到数据, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 金额或者库存不对
                    if (1 != europeProduct.getPrice().compareTo(BigDecimal.ZERO) || 0 >= europeProduct.getStock()) {
                        log.info("--------------- 实时查询buyer商品, 商品金额不是正常值, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 构建商品
                    StoreProductCrmebRequest storeProductCrmebRequest = buildEuropeProduct(europeProduct);
                    // 处理价格
                    storeProductCrmebRequest = sourceProductUtil.priceAdjustEurope2Crmeb(storeProductCrmebRequest);
                    saveProduct(storeProductCrmebRequest, storeProduct, europeProduct.getStock());
                    // IM商品
                } else if (ProductTypeEnum.valueOf(storeProduct.getIsEurope()) == ProductTypeEnum.IM) {
                    String id = barCode.substring(4, barCode.length());
                    SystemConfig systemConfig = systemConfigService.getOne(Wrappers.<SystemConfig>lambdaQuery()
                            .eq(SystemConfig::getName, Constants.IM_TOKEN)
                            .last("LIMIT 1")
                    );
//                    ImProductResDTO imProductResDTO = productUtil.getImProduct(Arrays.asList(id), systemConfig);
                    ImProductInfoResDTO imProductResDTO = productUtil.getImProductInfo(Collections.singletonList(id), systemConfig);
                    // 判定token失效
                    if (!imProductResDTO.getSuccess() && imProductResDTO.getError().contains("access-token")) {
                        systemConfig = productUtil.getImToken(systemConfig);
//                        imProductResDTO = productUtil.getImProduct(Arrays.asList(id), systemConfig);
                        imProductResDTO = productUtil.getImProductInfo(Collections.singletonList(id), systemConfig);
                    }
                    // 没有查询到商品
//                    List<ImProductDTO> imProductDTOs = imProductResDTO.getImProductDTOs();
                    List<ImProductInfoDTO> imProductDTOs = imProductResDTO.getImProductDTOs();
                    if (CollectionUtils.isEmpty(imProductDTOs) || CollectionUtils.isEmpty(imProductDTOs.get(0).getItemIds())) {
                        log.info("--------------- 实时查询IM商品, 未取到数据, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    if (imProductDTOs.get(0).getStatus() != 1) {
                        log.info("--------------- 实时查询IM商品, 商品不可售状态, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
//                    // 库存不对
//                    List<ImProductItemDTO> items = imProductDTOs.get(0).getItems();
                    //查询商品item信息
                    ImItemResDTO imItemInfo = productUtil.getImItemInfo(imProductDTOs.get(0).getItemIds(), systemConfig);
                    if (!imItemInfo.getSuccess() && imItemInfo.getError().contains("access-token")) {
                        systemConfig = productUtil.getImToken(systemConfig);
                        imItemInfo = productUtil.getImItemInfo(imProductDTOs.get(0).getItemIds(), systemConfig);
                    }
                    //上架且库存大于0的items
                    List<ImItemDTO> itemList = imItemInfo.getImItemDTOs().stream().filter(e -> e.getStatus() == 1 && e.getQty() > 0).collect(Collectors.toList());
                    Integer stock = 0;
                    for (ImItemDTO item : itemList) {
                        stock += item.getQty();
                    }
                    if (0 >= stock) {
                        log.info("--------------- 实时查询IM商品, 商品无库存, 直接下架并返回, 商品barCode: {}---------------", barCode);
                        soldOut(storeProduct.getId());
                        return barCode;
                    }
                    // 构建商品
//                    StoreProductCrmebRequest storeProductCrmebRequest = buildImProduct(imProductDTOs.get(0), Constants.RATE_IM_2_CRMEB_FLOAT, Constants.RATE_IM_2_CRMEB, Constants.RATE_IM_2_CRMEB_COST);
                    StoreProductCrmebRequest storeProductCrmebRequest = buildImProductNew(imProductDTOs.get(0), itemList);
                    saveProduct(storeProductCrmebRequest, storeProduct, stock);
                }

                return barCode;
            }
        };

        try {
            Future<String> future = thread.submit(call);
            future.get(1000 * 10, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ex) {
            System.out.println("--------------- 实时获取商品信息超时 ---------------");
            ex.printStackTrace();
        } catch (Exception e) {
            System.out.println("--------------- 实时获取商品信息处理失败 ---------------");
            e.printStackTrace();
        }
    }

    /**
     * @param request
     * @param pageParamRequest
     * @return com.common.CommonPage
     * @author cyz
     * @date 2021/4/9 11:29
     */
    @SuppressWarnings("rawtypes")
    @Override
    public CommonPage selectZoneProductList(ProductRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        List<StoreProduct> storeProductList = dao.selectZoneProductList(request);
        CommonPage<StoreProduct> storeProductCommonPage = CommonPage.restPage(storeProductList);
        if (CollectionUtils.isEmpty(storeProductList)) {
            return CommonPage.restPage(new ArrayList<>());
        }
        List<ProductResponse> productResponseArrayList = new ArrayList<>();
        //处理返回数据
        dealProductResponse(storeProductList, productResponseArrayList);

        CommonPage<ProductResponse> productResponseCommonPage = CommonPage.restPage(productResponseArrayList);
        BeanUtils.copyProperties(storeProductCommonPage, productResponseCommonPage, "list");
        return productResponseCommonPage;
    }

    private void saveProduct(StoreProductCrmebRequest storeProductCrmebRequest, StoreProduct storeProduct, Integer stock) {
        /****** 主表数据保存 *******/
        StoreProduct storeProductUpdate = new StoreProduct();
        BeanUtils.copyProperties(storeProductCrmebRequest, storeProductUpdate);
        storeProductUpdate.setStock(stock);
        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                .eq(StoreProduct::getId, storeProduct.getId())
                .set(StoreProduct::getPrice, storeProductUpdate.getPrice())
                .set(null != storeProductUpdate.getPromotePrice(), StoreProduct::getPromotePrice, storeProductUpdate.getPromotePrice())
                .set(null != storeProductUpdate.getVipPrice(), StoreProduct::getVipPrice, storeProductUpdate.getVipPrice())
                .set(null != storeProductUpdate.getOtPrice(), StoreProduct::getOtPrice, storeProductUpdate.getOtPrice())
                .set(null != storeProductUpdate.getPostage(), StoreProduct::getPostage, storeProductUpdate.getPostage())
                .set(null != storeProductUpdate.getKeyword(), StoreProduct::getKeyword, storeProductUpdate.getKeyword())
                .set(null != storeProductUpdate.getBrandId(), StoreProduct::getBrandId, storeProductUpdate.getBrandId())
                .set(null != storeProductUpdate.getBrandName(), StoreProduct::getBrandName, storeProductUpdate.getBrandName())
                .set(null != storeProductUpdate.getGiveIntegral(), StoreProduct::getGiveIntegral, storeProductUpdate.getGiveIntegral())
                .set(null != storeProductUpdate.getCost(), StoreProduct::getCost, storeProductUpdate.getCost())
                .set(null != storeProductUpdate.getSourceCost(), StoreProduct::getSourceCost, storeProductUpdate.getSourceCost())
                .set(null != storeProductUpdate.getCreateTime(), StoreProduct::getCreateTime, storeProductUpdate.getCreateTime())
                .set(null != storeProductUpdate.getLastPushTime(), StoreProduct::getLastPushTime, storeProductUpdate.getLastPushTime())
//                .set(null != storeProductUpdate.getIsEurope(), StoreProduct::getIsEurope, storeProductUpdate.getIsEurope())
                .set(null != storeProductUpdate.getTmall(), StoreProduct::getTmall, storeProductUpdate.getTmall())
                .set(StoreProduct::getIsShow, true)
                .set(StoreProduct::getStock, stock));
        Integer productId = storeProduct.getId();
        /****** attr表保存 ********/
        storeProductAttrService.removeByProductId(productId);
        List<StoreProductAttr> attrs = storeProductCrmebRequest.getAttr();
        attrs.forEach(e -> {
            e.setProductId(productId);
            e.setBarCode(storeProduct.getBarCode());
            e.setAttrValues(StringUtils.strip(e.getAttrValues().replace("\"", ""), "[]"));
        });
        storeProductAttrService.saveBatch(attrs);
        /****** value表保存 *********/
//        List<StoreProductAttrValue> dbStoreProductAttrValues = storeProductAttrValueService.list(Wrappers.<StoreProductAttrValue>lambdaQuery().eq(StoreProductAttrValue::getProductId, productId));
//        Map<String, StoreProductAttrValue> dbStoreProductAttrValueMap = dbStoreProductAttrValues.stream().collect(Collectors.toMap(StoreProductAttrValue::getSourceSkuId, s -> s, (value1, value2 )->{return value1;}));
        // 删除所有value
        storeProductAttrValueService.removeByProductId(productId);
        List<StoreProductAttrValueRequest> storeProductAttrValuesRequest = storeProductCrmebRequest.getAttrValue();
        List<StoreProductAttrValue> values = new ArrayList<>();
        for (StoreProductAttrValueRequest attrValuesRequest : storeProductAttrValuesRequest) {
            attrValuesRequest.setProductId(storeProduct.getId());
            attrValuesRequest.setBarCode(storeProduct.getBarCode());
            StoreProductAttrValue spav = new StoreProductAttrValue();
            BeanUtils.copyProperties(attrValuesRequest, spav);
            List<String> skuList = new ArrayList<>();
            for (Map.Entry<String, String> vo : attrValuesRequest.getAttrValue().entrySet()) {
                skuList.add(vo.getValue());
                spav.setSuk(String.join(",", skuList));
            }
            spav.setAttrValue(JSON.toJSONString(attrValuesRequest.getAttrValue()));
//            StoreProductAttrValue tempValue = dbStoreProductAttrValueMap.get(spav.getSourceSkuId());
//            if (null != tempValue) {
//                spav.setId(tempValue.getId());
//            }
            values.add(spav);
        }
        storeProductAttrValueService.saveBatch(values);
        /****** result表保存 ******/
        storeProductAttrResultService.remove(Wrappers.<StoreProductAttrResult>lambdaQuery().eq(StoreProductAttrResult::getProductId, productId));
        StoreProductAttrResult attrResult = new StoreProductAttrResult(/*0, */storeProduct.getId(), systemAttachmentService.clearPrefix(JSON.toJSONString(storeProductCrmebRequest.getAttrValue())), Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)), Constants.PRODUCT_TYPE_NORMAL, storeProduct.getBarCode());
        storeProductAttrResultService.save(attrResult);
        /****** Description表保存 ******/
        StoreProductDescription dbDescription = storeProductDescriptionService.getOne(Wrappers.<StoreProductDescription>lambdaQuery()
                .eq(StoreProductDescription::getProductId, productId)
                .last("LIMIT 1")
        );
        StoreProductDescription storeProductDescription = StoreProductDescription.getDescriptionByCrmeb(storeProductCrmebRequest);
        storeProductDescription.setId(ObjectUtil.isNotNull(dbDescription) ? dbDescription.getId() : null);
        storeProductDescription.setProductId(productId);
        storeProductDescriptionService.saveOrUpdate(storeProductDescription);

    }

    private StoreProductCrmebRequest buildEuropeProduct(EuropeProduct europeProduct) {
        List<EuropeProductSkuMerged> list = europeProduct.getSkuMergedList();
        // 规格处理
        StoreProductAttr storeProductAttr = new StoreProductAttr();
        storeProductAttr.setAttrName("尺寸");
        storeProductAttr.setType(0);
        StoreProductAttr storeProductAttrColor = new StoreProductAttr();
        storeProductAttrColor.setAttrName("颜色");
        storeProductAttrColor.setType(0);

        BigDecimal price = europeProduct.getPrice();
        BigDecimal referencePrice = europeProduct.getReferencePrice();
        List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
        List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();

        List<String> valueList = new ArrayList<>();
        List<String> valueColorList = new ArrayList<>();
        list.forEach(skuMerged -> {
            StoreProductAttrValueRequest storeProductAttrValueRequest = new StoreProductAttrValueRequest();
            storeProductAttrValueRequest.setImage(europeProduct.getGoodsImg());
            storeProductAttrValueRequest.setPrice(price);
            storeProductAttrValueRequest.setOtPrice(referencePrice);
            storeProductAttrValueRequest.setCost(price);
            storeProductAttrValueRequest.setStock(skuMerged.getStock());
            storeProductAttrValueRequest.setSourceSkuId(skuMerged.getSkuId());

            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
            List<String> suk = new ArrayList<String>();
            if (StringUtils.isNotBlank(skuMerged.getColor())) {
                linkedMap.put("颜色", skuMerged.getColor());
                if (!valueColorList.contains(skuMerged.getColor())) {
                    valueColorList.add(skuMerged.getColor());
                }
                suk.add(skuMerged.getColor());
            }
            if (StringUtils.isNotBlank(skuMerged.getSize())) {
                linkedMap.put("尺寸", skuMerged.getSize());
                if (!valueList.contains(skuMerged.getSize())) {
                    valueList.add(skuMerged.getSize());
                }
                suk.add(skuMerged.getSize());
            }
            storeProductAttrValueRequest.setSuk(String.join(",", suk));
            storeProductAttrValueRequest.setAttrValue(linkedMap);
            attrValueList.add(storeProductAttrValueRequest);
        });
        if (CollectionUtils.isNotEmpty(valueColorList)) {
            storeProductAttrColor.setAttrValues(String.join(",", valueColorList));
            attrList.add(storeProductAttrColor);
        }
        if (CollectionUtils.isNotEmpty(valueList)) {
            storeProductAttr.setAttrValues(String.join(",", valueList));
            attrList.add(storeProductAttr);
        }

        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        productRequest.setAttr(attrList);
        productRequest.setAttrValue(attrValueList);
        productRequest.setMerId(CrmebMerchantEnums.IM.getMerchantId());
        productRequest.setStoreInfo("");
        productRequest.setKeyword(europeProduct.getCode());
        List<EuropeProductSku> europeProductSku = europeProduct.getSkuList();
        productRequest.setContent(europeProductSku.get(0).getComposition());
        productRequest.setStoreName(europeProduct.getGoodsName());
        // 品牌对应
        StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                .eq(StoreBrand::getOtherId, europeProduct.getBrandId())
                .eq(StoreBrand::getType, 2)
                .eq(StoreBrand::getStatus, true)
                .eq(StoreBrand::getIsDeleted, false)
                .last("LIMIT 1")
        );
        StoreBrand storeBrand = null;
        if (null != buyerStoreBrand && null != buyerStoreBrand.getSuperId()) {
            storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
        }
        if (null != storeBrand) {
            productRequest.setBrandId(storeBrand.getId());
            productRequest.setBrandName(storeBrand.getEnName());
        }

        productRequest.setPrice(price);
        productRequest.setOtPrice(referencePrice);
        productRequest.setCost(price);

        CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                .eq(CategoryMatch::getType, CategoryTypeEnum.EUROPE)
                .eq(CategoryMatch::getOthCategoryId, europeProduct.getCategoryId())
                .last("LIMIT 1")
        );
        Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 0;
        productRequest.setCateId(categoryId);
        productRequest.setCateIds(Arrays.asList(categoryId));
        productRequest.setImage(europeProduct.getGoodsImg());
        productRequest.setBarCode(BarCodeEnum.EUROPE.getCode().toString() + europeProduct.getGoodId());
        // 商品图片
        if (StringUtils.isNotEmpty(europeProduct.getGallery())) {
            JSONArray arr = (JSONArray) JSONArray.parse(europeProduct.getGallery());
            List<String> sliderImages = new ArrayList<String>();
            if (!CollectionUtils.isEmpty(arr)) {
                arr.forEach(val -> {
                    JSONObject json = (JSONObject) val;
                    sliderImages.add(String.valueOf(json.get("img_original")));
                });
            }
            productRequest.setSliderImage(JSONObject.toJSONString(sliderImages));
        }
        productRequest.setIsShow(true);
        productRequest.setSpecType(true);
        // 发货地欧洲
        productRequest.setTempId(3);
        productRequest.setUnitName("件");
        // 是否服务商
        if (null != europeProduct.getSupplierId() && SuppliersIdEnum.EASY_FASHION.getCode().equals(europeProduct.getSupplierId() + "")) {
            productRequest.setMerUse(true);
        }
        productRequest.setSourceCost(price);

        //供应商
        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                .eq(Supplier::getSuppliersName, "1MAG")
                .last("LIMIT 1")
        );
        if (null != supplier) {
            productRequest.setSuppliersId(supplier.getId());
            productRequest.setSuppliersName(supplier.getSuppliersName());
        }
        productRequest.setIsEurope(ProductTypeEnum.EUROPE.getCode());
        productRequest.setLastPushTime(new Date());
        return productRequest;
    }

    private StoreProductCrmebRequest buildImProductNew(ImProductInfoDTO imProductDTO, List<ImItemDTO> itemList) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        try {
            ImItemDTO minSku = itemList.stream().min(Comparator.comparing(ImItemDTO::getSalePrice)).get();
            // 成本价
            PriceResult priceResult = priceUtil.eur2Rmb(minSku.getSalePrice());
            BigDecimal erpPrice = priceResult.getPrice();
            // 市场价
            BigDecimal retailPrice = minSku.getRetailPrice();
            // 品牌对应 (IM标准商品 type = 1)
            StoreBrand storeBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getId, imProductDTO.getBrandId())
                    .eq(StoreBrand::getType, ProductTypeEnum.INSIDE)
                    .last("LIMIT 1")
            );
            // 5429 IM标准其他品牌
            if (null == storeBrand) {
                storeBrand = storeBrandService.getById(5429);
            }
            /***** 处理对象构建 *******/
            String barCode = BarCodeEnum.IM.getCode() + imProductDTO.getProductId().toString();
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
            for (ImItemDTO sku : itemList) {
                // 成本价
                BigDecimal erpSkuPrice = priceUtil.eur2Rmb(sku.getSalePrice()).getPrice();
                // 市场价
                BigDecimal retailSkuPrice = sku.getRetailPrice();
                // 销售价(计算后)
                BigDecimal adjustSkuPrice = erpSkuPrice;
                // 成本价(计算后)
                BigDecimal adjustSkuCost = erpSkuPrice;

                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setSourceSkuId(sku.getItemId());
                storeProductAttrValue.setSuk(sku.getSize());
                storeProductAttrValue.setStock(sku.getQty());
                storeProductAttrValue.setPrice(adjustSkuPrice);
                if (imProductDTO.getImages().size() > 0) {
                    storeProductAttrValue.setImage(imProductDTO.getImages().get(0));
                }
                storeProductAttrValue.setCost(adjustSkuCost);
                storeProductAttrValue.setSourceCost(erpSkuPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(retailSkuPrice);

                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(sku.getSize())) {
                    linkedMap.put("尺寸", sku.getSize());
                }
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);
                // attr对象
                if (CollectionUtils.isEmpty(attrList)) {
                    StoreProductAttr attr = new StoreProductAttr();
                    attr.setProductId(imProductDTO.getProductId());
                    attr.setAttrName("尺寸");
                    attr.setAttrValues(sku.getSize());
                    attr.setBarCode(barCode);
                    attrList.add(attr);
                } else {
                    StoreProductAttr attr = attrList.get(0);
                    attr.setAttrValues(attr.getAttrValues() + "," + sku.getSize());
                }
            }

            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.IM.getMerchantId());
            productRequest.setContent(imProductDTO.getDescription());
            productRequest.setKeyword(imProductDTO.getDesignerId());
            productRequest.setStoreInfo("");
            productRequest.setStoreName(imProductDTO.getName());
            if (null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(erpPrice);
            productRequest.setOtPrice(retailPrice);
            productRequest.setCost(erpPrice);
            productRequest.setSourceCost(erpPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(2);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier::getSuppliersName, CrmebMerchantEnums.IM.getMerchantName())
                    .last("LIMIT 1")
            );
            if (null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            productRequest.setBarCode(barCode);
            // 分类 (IM type = 1)
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch::getType, CategoryTypeEnum.XUNWU)
                    .eq(CategoryMatch::getId, imProductDTO.getCategoryId())
                    .last("LIMIT 1")
            );
            //1859 (IM标准 其他 其他)
            Integer categoryId = null != categoryMatch ? categoryMatch.getId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            if (imProductDTO.getImages().size() > 0) {
                productRequest.setImage(imProductDTO.getImages().get(0));
                productRequest.setSliderImage(JSON.toJSONString(imProductDTO.getImages()));
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.IM.getCode());
            productRequest.setUnitName("件");
            productRequest.setComposition(imProductDTO.getComposition());
            productRequest.setDimension(imProductDTO.getDimension());
            productRequest.setColorCode(imProductDTO.getColorCode());
            productRequest.setSeasonCode(imProductDTO.getSeasonCode());
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return productRequest;
    }

    private StoreProductCrmebRequest buildImProduct(ImProductDTO imProductDTO, String rateFloat, String rate, String rateCost) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = null;
        List<ImProductItemDTO> items = imProductDTO.getItems();
        try {
            ImProductItemDTO minSku = items.stream().min(Comparator.comparing(ImProductItemDTO::getSalePrice)).get();
            // 成本价
            PriceResult priceResult = priceUtil.eur2Rmb(minSku.getSalePrice());
            BigDecimal erpPrice = priceResult.getPrice();
            // 市场价
            BigDecimal retailPrice = minSku.getRetailPrice();
            // 销售价(计算后)
            BigDecimal adjustPrice = PriceUtil.calePrice(new BigDecimal(rateFloat).multiply(erpPrice), rate);
            // 成本价(计算后)
            BigDecimal adjustCost = PriceUtil.calePrice(erpPrice, rateCost);
            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand::getOtherId, imProductDTO.getBrandId())
                    .eq(StoreBrand::getType, 5)
                    .last("LIMIT 1")
            );
            StoreBrand storeBrand = null;
            if (null != buyerStoreBrand) {
                if (null != buyerStoreBrand.getSuperId()) {
                    storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
                }
            }
            // 处理单独品牌价格(无法做成配置的)
            if (null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
                adjustPrice = PriceUtil.calePrice(retailPrice, "0.65");
            }

            /***** 处理对象构建 *******/
            List<StoreProductAttr> attrList = new ArrayList<StoreProductAttr>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<StoreProductAttrValueRequest>();
            for (ImProductItemDTO sku : items) {
                Integer productId = imProductDTO.getProductId();
                String barCode = BarCodeEnum.IM.getCode() + productId.toString();

                // 成本价
                BigDecimal erpSkuPrice = priceUtil.eur2Rmb(sku.getSalePrice()).getPrice();
                // 市场价
                BigDecimal retailSkuPrice = sku.getRetailPrice();
                // 销售价(计算后)
                BigDecimal adjustSkuPrice = PriceUtil.calePrice(new BigDecimal(rateFloat).multiply(erpSkuPrice), rate);
                // 成本价(计算后)
                BigDecimal adjustSkuCost = PriceUtil.calePrice(erpSkuPrice, rateCost);
                // 处理单独品牌价格(无法做成配置的)
                if (null != storeBrand && "13De Marzo".equals(storeBrand.getEnName())) {
                    adjustSkuPrice = PriceUtil.calePrice(retailSkuPrice, "0.65");
                }

                // value对象
                StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
                storeProductAttrValue.setProductId(productId);
                storeProductAttrValue.setSourceSkuId(sku.getItemId());
                storeProductAttrValue.setSuk(sku.getSize());
                storeProductAttrValue.setStock(sku.getQty());
                storeProductAttrValue.setPrice(adjustSkuPrice);
                storeProductAttrValue.setImage(JSON.toJSONString(imProductDTO.getImages()));
                storeProductAttrValue.setCost(adjustSkuCost);
                storeProductAttrValue.setSourceCost(erpSkuPrice);
                storeProductAttrValue.setBarCode(barCode);
                storeProductAttrValue.setOtPrice(retailSkuPrice);

                LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
                if (StringUtils.isNotBlank(sku.getSize())) {
                    linkedMap.put("尺寸", sku.getSize());
                }
                storeProductAttrValue.setAttrValue(linkedMap);
                attrValueList.add(storeProductAttrValue);

                // attr对象
                if (CollectionUtils.isEmpty(attrList)) {
                    StoreProductAttr attr = new StoreProductAttr();
                    attr.setProductId(productId);
                    attr.setAttrName("尺寸");
                    attr.setAttrValues(sku.getSize());
                    attr.setBarCode(barCode);
                    attrList.add(attr);
                } else {
                    StoreProductAttr attr = attrList.get(0);
                    attr.setAttrValues(attr.getAttrValues() + "," + sku.getSize());
                }
            }

            productRequest = new StoreProductCrmebRequest();
            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.IM.getMerchantId());
            productRequest.setContent(imProductDTO.getDescription());
            productRequest.setKeyword(imProductDTO.getDesignerId());
            productRequest.setStoreInfo(imProductDTO.getDescription());
            productRequest.setStoreName(imProductDTO.getName());
            if (null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(adjustPrice);
            productRequest.setOtPrice(retailPrice);
            productRequest.setCost(adjustCost);
            productRequest.setSourceCost(erpPrice);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(2);

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier::getSuppliersName, CrmebMerchantEnums.IM.getMerchantName())
                    .last("LIMIT 1")
            );
            if (null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch::getType, CategoryTypeEnum.IM)
                    .eq(CategoryMatch::getOthCategoryId, imProductDTO.getCategoryId())
                    .last("LIMIT 1")
            );
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 0;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setBarCode(BarCodeEnum.IM.getCode() + imProductDTO.getProductId().toString());
            List<String> gallery = imProductDTO.getImages();
            if (gallery.size() > 0) {
                productRequest.setImage(gallery.get(0).toString());
                productRequest.setSliderImage(JSON.toJSONString(gallery));
            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(true);
            productRequest.setIsEurope(ProductTypeEnum.IM.getCode());
            productRequest.setUnitName("件");
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return productRequest;
    }

    /**
     * 商品下架
     *
     * @param @param id
     * @return void
     * @throws
     * @Description:
     * @author daigb
     */
    private void soldOut(Integer id) {
        storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate().eq(StoreProduct::getId, id).set(StoreProduct::getIsShow, 0));
    }

    @Override
    public void calcProductSuppliersCount() {
        dao.ofProductSuppliersCount();
        dao.calcProductSuppliersCount();
    }

    @Override
    public void delProductException() {
        dao.delProductException();
    }

    @Override
    @Async("taskExecutor")
    public void autoDownProductTask(Integer merId) {
        log.info("--------------- 异步上架商户商品权限: {} ---------------", merId);
        List<ChannelMerchant> merchants = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaUpdate()
                .eq(ChannelMerchant::getAutomaticShelves, false)
                .eq(null != merId, ChannelMerchant::getId, merId)
        );

        for (ChannelMerchant merchant : merchants) {
            Integer mId = merchant.getId();
            JSONArray supplierIds = JSONArray.parseArray(merchant.getSuppliersIds());
            JSONArray brandIds = JSONArray.parseArray(merchant.getBrandIds());

            dao.autoDownProductTask(TableNameUtil.getProductMerName(mId), mId, supplierIds, brandIds);
        }

    }

    @Override
    @Async("taskExecutor")
    public void removeDownProduct(ChannelMerchant channelMerchant) {
        Integer merId = channelMerchant.getId();
        log.info("--------------- 异步删除商品活跃表无权限商品记录: {} ---------------", merId);
        LambdaQueryWrapper<StoreProduct> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        Supplier supplier = supplierService.getSupplierBarcode(merId);
        List<String> suppliersIdList = JSON.parseArray(channelMerchant.getSuppliersIds(), String.class);
        List<String> brandIdsList = JSON.parseArray(channelMerchant.getBrandIds(), String.class);
        List<String> tempIdList = JSON.parseArray(channelMerchant.getTempId(), String.class);
        if(CollectionUtils.isNotEmpty(brandIdsList)){
            lambdaQueryWrapper.in(StoreProduct::getBrandId,brandIdsList);
        }
        if (CollectionUtils.isNotEmpty(suppliersIdList)) {
            if (null != supplier) {
                suppliersIdList.add(supplier.getId().toString());
            }
        }
        if (CollectionUtils.isNotEmpty(tempIdList)) {
            lambdaQueryWrapper.in(StoreProduct::getTempId, tempIdList);
        }
        lambdaQueryWrapper.and(
                a -> a.ne(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
                        .or(b -> b.eq(StoreProduct::getIsEurope, ProductTypeEnum.INSIDE)
                                .ne(StoreProduct::getMerId, merId)
                                .isNotNull(StoreProduct::getConvertIsEurope))
        );
        lambdaQueryWrapper.eq(StoreProduct::getIsShow, true);
        lambdaQueryWrapper.eq(StoreProduct::getIsDel, false);
        lambdaQueryWrapper.notInSql(StoreProduct::getId, "SELECT product_id FROM " + TableNameUtil.getProductMerName(merId) + " WHERE is_not_show = 1");
        lambdaQueryWrapper.gt(StoreProduct::getStock, 0);
        List<Integer> integerList = categoryMatchService.selectCategoryMatchDisable(merId).stream().map(CategoryMatch::getId).collect(Collectors.toList());
        lambdaQueryWrapper.notIn(CollectionUtils.isNotEmpty(integerList), StoreProduct::getCateId, integerList);
        storeSaleAnalysisDao.removeDownProduct(merId, lambdaQueryWrapper);
    }

    @Override
    @Async("taskExecutor")
    public void autoUpOrDownProductTask(Integer merId, Boolean isShow) {
        log.info("--------------- 异步同步商户商品权限: {} ---------------", merId);
        MybatisPlusConfig.tableNameMp.set(TableNameUtil.getProductMerName(merId));
        storeProductMerService.update(Wrappers.<StoreProductMer>lambdaUpdate()
                .eq(StoreProductMer::getIsSystemOut, true)
                .set(StoreProductMer::getIsNotShow, isShow)
        );
    }

    @Override
    public void batchRenewalMerTask(ChannelMerchantDTO entity, ChannelMerchant channelMerchant) {
        // 获取渠道商户原本的供应商id
        String suppliersIds = channelMerchantService.getById(channelMerchant).getSuppliersIds();
        Set<String> originalSupplierIds = new Gson().fromJson(suppliersIds, new TypeToken<Set<String>>(){}.getType());

        // 新供应商集合
        Set<String> newSupplierIds = new Gson().fromJson(entity.getSuppliersIds(), new TypeToken<Set<String>>(){}.getType());

        // 比对集合
        Set<String> addedSuppliers = new HashSet<>(newSupplierIds);
        addedSuppliers.removeAll(originalSupplierIds); // 新增的供应商ID
        Set<String> removedSuppliers = new HashSet<>(originalSupplierIds);
        removedSuppliers.removeAll(newSupplierIds); // 被移除的供应商ID

        // 输出结果
        log.info("新增的供应商ID: {}  -----===-----  被移除的供应商ID: {}", addedSuppliers, removedSuppliers);

        // 获取渠道商户表名
        String tableName = TableNameUtil.getProductMerName(channelMerchant.getId());

        try {
            // 检查是否有新增的供应商
            if (!addedSuppliers.isEmpty()) {
                executor.execute(() -> handleAddedSuppliers(addedSuppliers, tableName));
            }
            // 检查是否有移除的供应商
            if (!removedSuppliers.isEmpty()) {
                executor.execute(() -> handleRemovedSuppliers(removedSuppliers, tableName));
            }
        } catch (Exception e) {
            log.error("处理供应商更新时错误!!! ", e);
        }
    }

    // 异步增加新供应商商品
    private void handleAddedSuppliers(Set<String> addedSuppliers, String tableName) {
        for (String supplierId : addedSuppliers) {
            //新增的供应商
            List<StoreProduct> list = storeProductService.lambdaQuery()
                    .eq(StoreProduct::getSuppliersId, supplierId)
                    .eq(StoreProduct::getIsShow, 1).list();
            for(StoreProduct product : list){
                if(productUtil.checkShippingTemp(product)) { //校验运费模板信息
                    StoreProductMer storeMerProduct = new StoreProductMer();
                    storeMerProduct.setProductId(product.getId());
                    storeMerProduct.setIsBest(product.getIsBest());
                    storeProductMerService.saveOrUpdateGoods(tableName, storeMerProduct);
                }
            }
        }

    }

    // 异步移除对应供应商的商品
    private void handleRemovedSuppliers(Set<String> removedSuppliers, String tableName) {
        for (String supplierId : removedSuppliers) {
            //移除的供应商
            List<StoreProduct> list = storeProductService.lambdaQuery().eq(StoreProduct::getSuppliersId, supplierId).list();
            List<Integer> productIds = list.stream().map(StoreProduct::getId).collect(Collectors.toList());
            if(productIds.size() > 0) {
                storeProductMerService.removeGoods(tableName, productIds);
            }
        }
    }

}
